#!/bin/bash

# Set release number
#
# Copyright 2019 Frank Heckenbach <f.heckenbach@fh-soft.de>
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

set -e

die ()
{
  echo "$*" >&2
  exit 1
}

[ "$#" = 2 ] || die "Usage: $(basename "$0") version description"
egrep -q "^[0-9]+.[0-9]+.[0-9]+$" <<< "$1" || die "invalid version format (x.y.z)"

[ "$CHANGELOG_NAME" ] || die "Please set CHANGELOG_NAME"

[ -e src/FTLibrary.cpp ] || die "This script must be invoked in the main FTGL source directory."

description="$2"
new="$1"
major="${new%%.*}"
minor="${new#*.}"
micro="${minor#*.}"
minor="${minor%%.*}"

prev="$(sed -En '/.* Release ([0-9]+.[0-9]+.[0-9]+)[ -]*$/{s//\1/p;q;}' NEWS)"
pmajor="${prev%%.*}"
pminor="${prev#*.}"
pmicro="${pminor#*.}"
pminor="${pminor%%.*}"

[[ "$((major != pmajor ? major > pmajor :
       minor != pminor ? minor > pminor :
                         micro > pmicro))" -eq 1 ]] || die "new version must be greater than old version ($prev)"

! fgrep "version $new." ChangeLog || die "new version already mentioned in ChangeLog"

[ -z "$(git status --porcelain)" ] || die "Please commit previous changes first."

sed -Ei "s/(AC_INIT\(FTGL, )[0-9]+.[0-9]+.[0-9]+(, )/\1$new\2/;
         s/(LT_MAJOR=\")[0-9]+(\")/\1$major\2/;
         s/(LT_MINOR=\")[0-9]+(\")/\1$minor\2/;
         s/(LT_MICRO=\")[0-9]+(\")/\1$micro\2/" configure.ac

sed -Ei "s/(SET\(VERSION_SERIES )[0-9]+(\))/\1$major\2/;
         s/(SET\(VERSION_MAJOR )[0-9]+(\))/\1$minor\2/;
         s/(SET\(VERSION_MINOR )[0-9]+(\))/\1$micro\2/" CMakeLists.txt

sed -Ei "s/(VERSIONNBR=)[0-9]+.[0-9]+.[0-9]+/\1$new/" ppa_upload.sh

sed -Ei "s/(#define PACKAGE_VERSION \")[0-9]+.[0-9]+.[0-9]+(\")/\1$new\2/" msvc/config.h

sed -Ei "s/(SHLIBVER := ).*$/\1$new/" debian/rules

sed -i "1i\\
$(date +"%F %H:%M")  $CHANGELOG_NAME\\
\\
  * NEWS, configure.ac, CMakeLists.txt, ppa_upload.sh, msvc/config.h, debian/rules:\\
    * Mark package as being version $new.\\

" ChangeLog

sed -i "0,/--- .* Release /{/--- .* Release /i\\
--- $(date +"%F")  Release $new                                      ---\\
----------------------------------------------------------------------\\
\\
    * ${description//\n/\n    * }\\
\\
----------------------------------------------------------------------
;}" NEWS

PAGER= git diff
git add -A
git commit -m "$description"

echo
echo "*** New release number set; now push and create release tag."
